<template>
  <div class="addSubject">
    <!-- 新增学科 -->
    <el-dialog :visible.sync="dialogFormVisible" width="600px" :center="true">
      <div slot="title" class="title">{{mode=="add" ? '新增学科' : '编辑学科'}}</div>
      <el-form :model="form" :rules="rules" ref="form" label-width="110px">
        <el-form-item label="学科编号" prop="rid">
          <el-input v-model="form.rid"></el-input>
        </el-form-item>
        <el-form-item label="学科名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="学科简称" prop="short_name">
          <el-input v-model="form.short_name"></el-input>
        </el-form-item>
        <el-form-item label="学科简介" prop="intro">
          <el-input v-model="form.intro"></el-input>
        </el-form-item>
        <el-form-item label="学科备注" prop="remark">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSub, editSub } from "@/api/subject.js";
export default {
  props:['mode'],
  data() {
    return {
      dialogFormVisible: false,
      form: {
        rid: "",
        name: "",
        short_name: "",
        intro: "",
        remark: ""
      },
      rules: {
        rid: [{ required: true, message: "请填写学科编号", trigger: "change" }],
        name: [
          { required: true, message: "学科名称不能为空哦", trigger: "change" }
        ]
      }
    };
  },

  watch: {
    dialogFormVisible(newVal) {
      if (newVal == false) {
        // 清空表单和表单验证规则
        this.$refs.form.resetFields();
      }
    }
  },

  created() {
    console.log(this.mode);
  },

  methods: {
    submit() {
      // 全局验证
      this.$refs.form.validate(result => {
        if (result) {
          // 新增
          if (this.mode == "add") {
            // 通过验证
            addSub(this.form).then(() => {
              // console.log('新增学科', res);
              this.$message.success("学科新增成功");
              this.dialogFormVisible = false;
              this.$parent.search();
            });
          } else {
            // 编辑
            editSub(this.form).then(res => {
              console.log(res);
              this.$message.success("学科信息修改成功");
              this.dialogFormVisible = false;
              // 刷新数据
              this.$parent.getData();
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="less">
.addSubject {
  .el-dialog__header {
    padding: 0;
  }

  .title {
    width: 100%;
    height: 53px;
    background: linear-gradient(to right, #01c5fa, #1394fa);
    line-height: 53px;
    color: #fff;
    font-size: 18px;
  }

  .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
    font-size: 12px;
  }
}
</style>